<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>react-hook 项目中实践 | 一枚前端小菜鸟的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="引言本文将介绍一些在日常开发中使用react hooks的心得体会，将着重介绍两个hooks的使用：useState 和 useEffect这两个比较常用的使用方式。 1、在react class组件如此成熟的时代，我们为什么还要使用react hooks呢， 首先我们要明确几点：  react hooks完全是可选择的，你可以重写老的冗余组件，可以在新的组件使用，也可以啥都不学啥都不做，当一条咸">
<meta property="og:type" content="article">
<meta property="og:title" content="react-hook 项目中实践">
<meta property="og:url" content="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/index.html">
<meta property="og:site_name" content="一枚前端小菜鸟的博客">
<meta property="og:description" content="引言本文将介绍一些在日常开发中使用react hooks的心得体会，将着重介绍两个hooks的使用：useState 和 useEffect这两个比较常用的使用方式。 1、在react class组件如此成熟的时代，我们为什么还要使用react hooks呢， 首先我们要明确几点：  react hooks完全是可选择的，你可以重写老的冗余组件，可以在新的组件使用，也可以啥都不学啥都不做，当一条咸">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://assets.che300.com/wiki/2021-03-05/1614932915835-image.png">
<meta property="article:published_time" content="2021-06-18T06:26:53.000Z">
<meta property="article:modified_time" content="2021-06-18T06:27:14.070Z">
<meta property="article:author" content="yywei">
<meta property="article:tag" content="菜鸟,前端,js,react,vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://assets.che300.com/wiki/2021-03-05/1614932915835-image.png">
  
    <link rel="alternate" href="/atom.xml" title="一枚前端小菜鸟的博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">一枚前端小菜鸟的博客</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">yywei的遇坑记录</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/weiyayun1995/weiyayun1995.git"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-react-hook-项目中实践" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/" class="article-date">
  <time class="dt-published" datetime="2021-06-18T06:26:53.000Z" itemprop="datePublished">2021-06-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      react-hook 项目中实践
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h3 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h3><p>本文将介绍一些在日常开发中使用react hooks的心得体会，将着重介绍两个hooks的使用：<code>useState</code> 和 <code>useEffect</code>这两个比较常用的使用方式。</p>
<p>1、在react class组件如此成熟的时代，我们为什么还要使用react hooks呢，</p>
<p>首先我们要明确几点：</p>
<ul>
<li>react hooks完全是<strong>可选择</strong>的，你可以重写老的冗余组件，可以在新的组件使用，也可以啥都不学啥都不做，当一条咸鱼🐟。</li>
<li>100% 向后兼容 Hooks不包含任何破坏式&lt;颠覆式&gt;更新。</li>
<li>class不会被移除，依然与hooks并存，但官方更建议使用hooks，<code>因为在大部分情况下凡是class能做到的hooks都能做到</code>。</li>
</ul>
<p>在使用react class组件时，<br>2、<strong>跨组件复用含状态（state）的逻辑十分困难</strong>，因为我们不得不通过实例对象<code>this</code>上挂载的各种方法来实现业务逻辑（如setState），而过多的<code>this</code>很容易让初级开发者产生一些疑惑（诸如这个this指向谁的问题，同样的问题也发生在vue2中）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614909245017-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<p>3、<strong>复杂的组件变得冗余</strong>，在项目的后期，class组件很可能变得难以维护，试想一下，一个上千行的组件，内部会有上百个函数，由于每个函数都有自己的作用域，所以如果我们想在这些方法中使用<code>state</code> <code>props</code>的属性，我们就得不停的重定义，而hooks的functionComponent特性，让我们避免了这种事情的发生，从而减少了代码重复也提高了效率。(在不断地研究后发现其实这样做会存在一些性能问题也不好说，但是对于大部分项目而言并不太影响性能)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614909741266-image.png)</span><br><span class="line">| ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-24&#x2F;16165811241037850.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<p>4、<strong>学习成本</strong><br>这也是<code>hooks</code>的优势之一，对于掌握<code>react</code>的同学来说这简直小菜一碟，对于还没有使用<code>react</code>的同学来说也不会太难，因为<code>vue3</code>与<code>react hooks</code>从思想设计程度上是一致的。当然，<code>react</code>多年来对比<code>vue</code>，业界普遍认为<code>react</code>上手较难，所以从招聘广告来看除了知名大厂使用<code>react</code>，其他公司用<code>vue</code>会更多，而<code>hooks</code>的出现一定程度上降低了难度。</p>
<p>5、<strong>hooks将逻辑更细粒度划分</strong>，就是使用hooks不仅仅可以封装带dom的组件，也可以封装一些公用的”响应式”逻辑方法（如实时监听返回一个用户登录状态，这个状态我们可以在任何hooks组件中复用），很显然class组件在处理这类事情的时候，写法稍微复杂一些。</p>
<h3 id="useState与useEffect"><a href="#useState与useEffect" class="headerlink" title="useState与useEffect"></a>useState与useEffect</h3><p>我们先简单介绍一下 <code>useState</code>与<code>useEffect</code> 是如何使用的 </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [demo1Name, setDemo1Name] = useState(<span class="string">&#x27;&#x27;</span>);</span><br></pre></td></tr></table></figure>
<p>返回一个两项数组，第一项为<code>useState</code>返回的最新值，第二项可以理解为 具名化的<code>setState</code>，我们通过传 空字符串 作为 <code>useState</code> 唯一的参数来将其初始化为 空字符串</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 声明多个 state 变量</span></span><br><span class="line"><span class="keyword">const</span> [age, setAge] = useState(<span class="number">42</span>);</span><br><span class="line"><span class="keyword">const</span> [fruit, setFruit] = useState(<span class="string">&#x27;banana&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> [todos, setTodos] = useState([&#123; <span class="attr">text</span>: <span class="string">&#x27;学习 Hook&#x27;</span> &#125;]);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>提示<br>如果你熟悉 <code>React class</code> 的生命周期函数，你可以把 <code>useEffect Hook</code> 看做 <code>componentDidMount</code>，<code>componentDidUpdate</code> 和 <code>componentWillUnmount</code> 这三个函数的组合。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 相当于每次都会触发 componentDidUpdate</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我一直在触发useEffect1&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只有组件初始化的时候触发 componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我初始化的时候触发了useEffect2&#x27;</span>)</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只要nameZyy变化了,以及初始化时就触发 类似于 vue中的 watch但比watch强大</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;因为nameZyy变化了，我触发了useEffect3&#x27;</span>)</span><br><span class="line">    &#125;, [nameZyy])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 只要nameXyb变化了,以及初始化时就触发</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;因为nameXyb变化了，我触发了useEffect4&#x27;</span>)</span><br><span class="line">    &#125;, [nameXyb])</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 组件销毁时触发return 中的函数 componentWillUnmount</span></span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 清除定时器、清除事件监听函数</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, [])</span><br></pre></td></tr></table></figure>
<p><img src="https://assets.che300.com/wiki/2021-03-05/1614932915835-image.png"></p>
<h3 id="每次组件更新相当于重新执行组件function"><a href="#每次组件更新相当于重新执行组件function" class="headerlink" title="每次组件更新相当于重新执行组件function"></a>每次组件更新相当于重新执行组件<code>function</code></h3><blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<ul>
<li><p>在<code>class</code>组件中，触发更新视图操作往往只需执行<code>render</code>函数以及特定<code>update</code>生命周期，它内部的状态通过<code>this</code>实例指向唯一内存地址，所以保证了组件状态在更新后的统一性。</p>
</li>
<li><p>在<code>hooks</code>中，没有<code>this</code>，触发视图渲染后，需要重新执行这个组件函数，所导致的后果便是内部声明的变量会全部重新定义一遍，所以<code>hooks</code>组件借助了<code>react</code> 内部的方法让该组件从无状态变为有状态（<code>useState</code>），在<code>useState</code>内部保存着一个你初始化时定义的 变量。</p>
</li>
</ul>
<p>为了更好的论证上面的理论，我这边借鉴了 <code>网易云团队</code>给出的概念 —— 类似动画帧的概念（我们将每次触发渲染称为一帧），更容易理解<code>hooks</code>的执行机制</p>
<h4 id="每一帧定义的变量方法都是独立的，前后互不影响"><a href="#每一帧定义的变量方法都是独立的，前后互不影响" class="headerlink" title="每一帧定义的变量方法都是独立的，前后互不影响"></a>每一帧定义的变量方法都是独立的，前后互不影响</h4><p>为了解释帧的概念，这里有个定时器的例子</p>
<blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Demo2</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> [num, setNum] = useState(<span class="number">0</span>);</span><br><span class="line">    <span class="comment">// componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setNum(num + <span class="number">1</span>) <span class="comment">// num一直是0，我拿的一直是第一帧即初始化时候的值</span></span><br><span class="line">            <span class="built_in">console</span>.log(num)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;, [])</span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(num,<span class="string">&#x27;我变成了1，之后一直是1，切不会触发渲染了&#x27;</span>)</span><br><span class="line">    &#125;,[num])</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo2&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;num&#125;&lt;/p&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上方demo2是如何执行的呢，<code>首先初始化第一帧</code><br>可以模拟为下方第一帧代码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Demo2_1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> num_1 = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">// componentDidMount</span></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setNum(num_1 + <span class="number">1</span>)</span><br><span class="line">            <span class="built_in">console</span>.log(num_1)</span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">    &#125;, [])</span><br><span class="line">    useEffect(<span class="function">()=&gt;</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(num_1,<span class="string">&#x27;我初始化的时候执行以下0，第二帧我变成了1，之后一直是1，切不会触发渲染了&#x27;</span>)</span><br><span class="line">    &#125;,[num_1])</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo2&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;num_1&#125;&lt;/p&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在demo2组件内部定义了 <code>num_1</code> 常量，两个 <code>useEffect</code> 函数，其中一个<code>useEffect</code> 只会在初始化的第一帧执行。<br>所导致的后果是：这个第一帧内部的代码就始终保持不变，即内部<code>setInterval</code>的回调函数中的变量num_1一直是0，从而导致<code>setNum</code>一直重复（0+1）  也导致了第二个<code>useEffect</code> console.log num_1 的值 只会增加到1，就不再触发渲染了。</p>
<blockquote>
<p>分享会跳转vscode</p>
</blockquote>
<p>如果上面的例子 你觉得没有说服力，ok！我给你一个网易大v的例子</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo3 = <span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; count &#125; = props;</span><br><span class="line">    <span class="keyword">const</span> handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            alert(count);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo3&quot;</span>&gt;</span><br><span class="line">            &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">            &lt;button onClick=&#123;handleClick&#125;&gt;点我弹我&lt;/button&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Demo3;</span><br></pre></td></tr></table></figure>
<p>我们通过<code>props</code>将<code>count</code>传入子组件，初始值为0，每隔一秒加1，我们点击 <code>点我弹我</code>按钮，alert的count值，发现并不是页面上还在自增的值，而是等于点击的<code>那一刻</code>的值。 <strong>从而论证了每一帧的值都是 独立的，就是一个普普通通的数据而已</strong>。</p>
<ul>
<li>当然这种情况只会在 hooks中出现，若使用class组件，由于this指向同一实例，this内部属性值是持续变化的。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Demo4</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">    handleClick = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            alert(<span class="built_in">this</span>.props.count);</span><br><span class="line">        &#125;, <span class="number">3000</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="function"><span class="title">render</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123;</span><br><span class="line">            count</span><br><span class="line">        &#125; = <span class="built_in">this</span>.props;</span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            &lt;Card title=<span class="string">&quot;demo4&quot;</span>&gt;</span><br><span class="line">                &lt;p&gt;&#123;count&#125;&lt;/p&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="built_in">this</span>.handleClick&#125;&gt;点我弹我<span class="number">4</span>&lt;/Button&gt;</span><br><span class="line">            &lt;/Card&gt;</span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><p>上面两个例子，通过动画帧的概念辅助理解每次触发<code>render</code>时 <code>hooks</code>函数重新定义内部变量，并且通过<code>useState</code>等方式，<code>react</code>帮我们维护了一组状态，这些状态独立于函数存放。</p>
<p>需要明确的是，我们通过<code>useState</code>解构出来的变量  作为函数中的一个常量，就是普通的数据，并不存在诸如数据绑定这样的操作来驱使 <code>DOM</code> 发生更新。在调用 hooks中的<code>setState</code> 后，<code>React</code> 将重新执行 <code>render</code> 函数，仅此而已。</p>
<h3 id="永远不要欺骗useEffect"><a href="#永远不要欺骗useEffect" class="headerlink" title="永远不要欺骗useEffect"></a>永远不要欺骗useEffect</h3><p>对于 useEffect 来说，执行的时机是完成所有的 <code>DOM</code> 变更并让浏览器渲染页面后</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Demo5 = <span class="function">(<span class="params">props</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123;</span><br><span class="line">        id</span><br><span class="line">    &#125; = props;</span><br><span class="line"></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(id, <span class="string">&#x27;我是demo5中的id值&#x27;</span>)</span><br><span class="line">            &#125;, <span class="number">100</span>)</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo5&quot;</span>&gt;</span><br><span class="line">            我是demo5 &#123;id&#125;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通常我们会有上面的这种需求，id是由接口动态返回的，demo5作为子组件他也要使用id请求一次其他的接口，这时，实际上我们依赖了动态的<code>id</code>，但是在子组件中这么写是无法获得最新的id值，因为子组件在<code>id</code>值发生变化的时候，就已经渲染完毕了。</p>
<p><strong>针对这种情况，我们有两种解决方案</strong><br>1、<code>useEffect</code>第二个参数的数组中加上<code>id</code>依赖，并做空保护。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (id) &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(id, <span class="string">&#x27;我是demo5中的id值&#x27;</span>)</span><br><span class="line">        &#125;, <span class="number">100</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;, [id])</span><br></pre></td></tr></table></figure>
<p>2、当<code>id</code>值发生变化后，再渲染子组件。<br>但是针对 诸如 wiki 这种 文章组件不会销毁的情况，则使用<code>hooks</code>的优势就体现出来了。</p>
<h3 id="useMemo的实践"><a href="#useMemo的实践" class="headerlink" title="useMemo的实践"></a>useMemo的实践</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-29&#x2F;16170023709952396.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; Button,Card &#125; <span class="keyword">from</span> <span class="string">&#x27;antd&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> [count, setCount] = useState(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">const</span> [val, setValue] = useState(<span class="string">&#x27;朱育仪&#x27;</span>);</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我又执行了&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count * <span class="number">100</span>; i++) &#123;</span><br><span class="line">            sum += i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo6&quot;</span>&gt;</span><br><span class="line">            &lt;h4&gt;&#123;count&#125;---&#123;add()&#125;&lt;/h4&gt;</span><br><span class="line">            &#123;val&#125;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;+<span class="number">1</span>&lt;/Button&gt;</span><br><span class="line">                &lt;input value=&#123;val&#125; onChange=&#123;<span class="function"><span class="params">event</span> =&gt;</span> setValue(event.target.value)&#125; /&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行上面的demo6，我们会发现，无论我们点击<code>Button</code>或者在<code>input</code>添加值，<code>add</code>函数都会执行，然而<code>add</code>函数与<code>val</code>并无关系，这就造成了性能的损耗。所以针对这种情况我们就需要使用 <code>useMemo</code>这个 hook。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> [count, setCount] = useState(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">const</span> [val, setValue] = useState(<span class="string">&#x27;朱育仪&#x27;</span>);</span><br><span class="line">    <span class="keyword">const</span> add = useMemo(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;我只有count变了，我才执行&#x27;</span>);</span><br><span class="line">        <span class="keyword">let</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; count * <span class="number">10</span>; i++) &#123;</span><br><span class="line">            sum += i;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;, [count])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card&gt;</span><br><span class="line">            &lt;h4&gt;&#123;count&#125;-&#123;add&#125;&lt;/h4&gt;</span><br><span class="line">            &#123;val&#125;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;Button onClick=&#123;<span class="function">() =&gt;</span> setCount(count + <span class="number">1</span>)&#125;&gt;+c1&lt;/Button&gt;</span><br><span class="line">                &lt;input value=&#123;val&#125; onChange=&#123;<span class="function"><span class="params">e</span> =&gt;</span> setValue(e.target.value)&#125; /&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此时只有当我们点击 <code>Button</code> 时再触发 <code>add</code> 函数，节省了性能的消耗。<br>这里有一张题库项目中的实践图</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614936725891-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>
<p>这里将列表筛选项进行了缓存，减少了不必要的渲染，从而提高性能。（原先的class组件其实没有考虑到这种问题）</p>
<p>在过去的<code>class</code>组件中，我们通过<code> shouldComponentUpdate</code> 判断当前属性和状态是否和上一次的相同，来避免组件不必要的更新。其中的比较是对于本组件的所有属性和状态而言的，无法根据 <code>shouldComponentUpdate</code> 的返回值来使该组件一部分 <code>elements</code> 更新，另一部分不更新。（公司所有的进件系统筛选项都有这个问题）<br>而函数组件中的 <code>useMemo</code> 其实就可以代替这一部分工作。</p>
<h3 id="强大的自定义hooks"><a href="#强大的自定义hooks" class="headerlink" title="强大的自定义hooks"></a>强大的自定义hooks</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; useEffect, useState, &#125; <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">useOnline</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> [online, setOnline] = useState(<span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line">    useEffect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> timer = <span class="built_in">setInterval</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            setOnline(<span class="function"><span class="params">c</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> !c</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;, <span class="number">3000</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">clearInterval</span>(timer)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, [])</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> online</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的hooks 比较特殊，它定义了一个 online状态，每三秒变化一次true false  来模拟用户在线或者离线。我们可以直接返回 该状态。<br>如何使用呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> () =&gt; &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> online = useOnline();</span><br><span class="line">    <span class="built_in">console</span>.log(online)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;Card title=<span class="string">&quot;demo8&quot;</span>&gt;</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &#123;online ? <span class="string">&#x27;我在线&#x27;</span> : <span class="string">&#x27;我离线&#x27;</span>&#125;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        &lt;/Card&gt;</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该示例中直接调用 <code>const online = useOnline();</code> ,即可获取到<code>online</code>的响应数据。<br>这就是自定义<code>hooks</code>的强大之处，聪明的开发者们也正是因为自定义<code>hooks</code>的存在，开发出了各种各样好用的<code>hooks</code></p>
<h3 id="关于父组件如何调取子组件方法"><a href="#关于父组件如何调取子组件方法" class="headerlink" title="关于父组件如何调取子组件方法"></a>关于父组件如何调取子组件方法</h3><p>使用<code>useRef useImperativeHandle forwardRef</code>配合使用达到<code>class</code>组件的效果</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">interface useRefTypes &#123;</span><br><span class="line">    getTopicList: <span class="function">() =&gt;</span> <span class="keyword">void</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> topicRef = useRef&lt;useRefTypes&gt;(<span class="literal">null</span>);</span><br><span class="line">...</span><br><span class="line"><span class="keyword">const</span> topicDom = (</span><br><span class="line">     &lt;div className=&#123;styles.describeContainer&#125;&gt;</span><br><span class="line">          &lt;Topic</span><br><span class="line">               dispatch=&#123;dispatch&#125;</span><br><span class="line">               subjectId=&#123;id&#125;</span><br><span class="line">               loading=&#123;loading&#125;</span><br><span class="line">               userId=&#123;_id&#125;</span><br><span class="line">               ref=&#123;topicRef&#125;</span><br><span class="line">          /&gt;</span><br><span class="line">     &lt;/div&gt;</span><br><span class="line">)</span><br><span class="line">...</span><br><span class="line"><span class="comment">// 提交并发布评论区</span></span><br><span class="line"><span class="keyword">const</span> submitAndTopic = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (!submitValue) &#123;</span><br><span class="line">        notification.warning(&#123;</span><br><span class="line">            message: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">            description: <span class="string">&#x27;请输入你的答案&#x27;</span></span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    confirm(&#123;</span><br><span class="line">        title: <span class="string">&#x27;提示&#x27;</span>,</span><br><span class="line">        content: <span class="string">&#x27;是否将答案同步到评论区？&#x27;</span>,</span><br><span class="line">        okText: <span class="string">&#x27;确定&#x27;</span>,</span><br><span class="line">        cancelText: <span class="string">&#x27;取消&#x27;</span>,</span><br><span class="line">        onOk: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            submit();</span><br><span class="line">            dispatch(&#123;</span><br><span class="line">                type: <span class="string">&#x27;subjectDetails/addTopic&#x27;</span>,</span><br><span class="line">                payload: &#123;</span><br><span class="line">                    subjectId: id,</span><br><span class="line">                    content: submitValue,</span><br><span class="line">                    parentTopicId: <span class="string">&#x27;topTopic&#x27;</span></span><br><span class="line">                &#125;,</span><br><span class="line">                callback: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                    <span class="keyword">if</span> (topicRef &amp;&amp; topicRef.current) &#123;</span><br><span class="line">                        <span class="keyword">if</span> (topicRef.current.getTopicList) &#123;</span><br><span class="line">                            topicRef.current.getTopicList();</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在父组件中使用<code>usRef</code>（上方代码）<br>在子组件中使用<code>useImperativeHandle forwardRef</code>（下方代码）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将方法包裹在forwardRef中</span></span><br><span class="line"><span class="keyword">const</span> Topic: React.FC&lt;propsType&gt; = forwardRef(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> &#123;</span><br><span class="line">...</span><br><span class="line">    useImperativeHandle(ref, <span class="function">() =&gt;</span> (&#123;</span><br><span class="line">        getTopicList</span><br><span class="line">    &#125;));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>将方法包裹在 <code>forwardRef</code> 中，内部调用 <code>useImperativeHandle</code> （<code>useImperativeHandle</code> 可以让你在使用 <code>ref</code> 时自定义暴露给父组件的实例值。在大多数情况下，应当避免使用 <code>ref</code> 这样的命令式代码。<code>useImperativeHandle</code> 应当与 <code>forwardRef</code> 一起使用。）</p>
<h3 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h3><p><a target="_blank" rel="noopener" href="https://react.docschina.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render">好学的艺宝在会前讨论中和我谈到的问题如下</a></p>
<h4 id="1、Hooks-会因为在渲染时创建函数而变慢吗？"><a href="#1、Hooks-会因为在渲染时创建函数而变慢吗？" class="headerlink" title="1、Hooks 会因为在渲染时创建函数而变慢吗？"></a>1、Hooks 会因为在渲染时创建函数而变慢吗？</h4><p>不会。在现代浏览器中，闭包和类的原始性能只有在极端场景下才会有明显的差别。<br>除此之外，可以认为 Hooks 的设计在某些方面更加高效：</p>
<ul>
<li><code>Hooks</code> 避免了 <code>class</code> 需要的额外开支，像是创建类实例和在构造函数中绑定事件处理器的成本。</li>
<li>符合语言习惯的代码在使用 <code>Hooks</code> 时不需要很深的组件树嵌套。这个现象在使用高阶组件、render props、和 context 的代码库中非常普遍。组件树小了，React 的<code>工作量</code>也随之减少。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614938038176-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-05&#x2F;1614927889461-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>
<p>我们将 只会在<code>useEffect</code>中执行的代码放置于<code>useEffect</code>回调函数内部，这样只有依赖值发生变化的时候才会执行<code>useEffect</code>内部函数声明。</p>
<h4 id="2、-只在最顶层使用-Hook-？"><a href="#2、-只在最顶层使用-Hook-？" class="headerlink" title="2、**只在最顶层使用 Hook**？"></a>2、**只在最顶层使用 <code>Hook</code>**？</h4><p>是的没错！！！<br>不要在<strong>循环</strong>，<strong>条件或嵌套函数</strong>中调用 <code>Hook</code>， 确保总是在你的 <code>React</code> 函数的最顶层调用他们。遵守这条规则，你就能确保 <code>Hook</code> 在每一次渲染中都按照同样的顺序被调用。这让 <code>React</code> 能够在多次的 <code>useState</code> 和 <code>useEffect</code> 调用之间保持 <code>hook</code> 状态的正确。</p>
<h3 id="参考文档"><a href="#参考文档" class="headerlink" title="参考文档"></a>参考文档</h3><p><a target="_blank" rel="noopener" href="https://react.docschina.org/docs/hooks-overview.html">react官方中文网</a><br><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904165500518414">https://juejin.cn/post/6844904165500518414</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_44753552/article/details/108329228">https://blog.csdn.net/qq_44753552/article/details/108329228</a><br><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/56975681">useCallback</a><br><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/412c874c5add">useEffect和useLayoutEffect的区别</a><br><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_39702483/article/details/110561916">addeventlistener事件参数_函数式编程看React Hooks(二)事件绑定副作用深度剖析</a><br><a target="_blank" rel="noopener" href="https://overreacted.io/zh-hans/why-do-hooks-rely-on-call-order/#%E7%BC%BA%E9%99%B7-2-%E5%91%BD%E5%90%8D%E5%86%B2%E7%AA%81">为什么顺序调用对 React Hooks 很重要？</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000023669309">vue3 watchEffect</a></p>
<p>3、异步回调中多次触发render问题<br><a target="_blank" rel="noopener" href="https://github.com/facebook/react/issues/18725">https://github.com/facebook/react/issues/18725</a></p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">|  ![](https:&#x2F;&#x2F;assets.che300.com&#x2F;wiki&#x2F;2021-03-17&#x2F;1615948305846-image.png)</span><br><span class="line">|_</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/" data-id="ckq7mlsw1000qdgt92kud8uk0" data-title="react-hook 项目中实践" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">前一篇</strong>
      <div class="article-nav-title">
        
          js数据类型及转换
        
      </div>
    </a>
  
  
    <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">后一篇</strong>
      <div class="article-nav-title">数字签名</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">六月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/05/">五月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/">js数据类型及转换</a>
          </li>
        
          <li>
            <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/">react-hook 项目中实践</a>
          </li>
        
          <li>
            <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/">数字签名</a>
          </li>
        
          <li>
            <a href="/2021/06/18/sendbeacon/">sendbeacon</a>
          </li>
        
          <li>
            <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/">js数据类型的判断</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2021 yywei<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>